import re

from django.contrib.auth.backends import ModelBackend

from .models import User


class UsernameMobileAuthBackend(ModelBackend):
    """自定义用户认证后端"""

    def authenticate(self, request, username=None, password=None, **kwargs):
        """重写认证authenticate"""

        # 获取username的对象，username可以使用户名也可以是手机号
        user = self.get_user_account(username)

        # 判断user对象密码是否正确
        if user and user.check_password(password):
            return user

    @staticmethod
    def get_user_account(username):
        """认证username是用户名还是手机号"""
        try:
            # 判断是否是手机号
            if re.match(r'^1[3-9]\d{9}$', username):
                # 查询用户名的对象
                user = User.objects.get(mobile=username)
            else:
                user = User.objects.get(username=username)
        except User.DoesNotExist:
            return None
        else:
            # 返回对象
            return user



